package com.gxuwz.stats.service.excelhandler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.impl.UserServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class UserListener extends AnalysisEventListener<User> implements ImportResultProvider {
    private final List<User> dataList = new ArrayList<>();
    private final UserServiceImpl userService;
    private boolean stopProcessing = false;

    private final String currentUsername;
    private final String currentRole;
    private final String currentDepartment;

    public UserListener(UserServiceImpl userService, String username, String role, String department) {
        this.userService = userService;
        this.currentUsername = username;
        this.currentRole = role;
        this.currentDepartment = department;
    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        if (stopProcessing) {
            return;
        }

        // 检查姓名是否为空或包含说明
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return;
        }
        if (user.getUsername().contains("说明") || user.getUsername().length() > 12) {
            stopProcessing = true;
            return;
        }

        // 权限验证：只有超级管理员可以导入用户
        if (!"超级管理员".equals(currentRole)) {
            return;
        }

        // 设置默认值
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        }
        if (user.getRole() == null || user.getRole().isEmpty()) {
            user.setRole("普通用户");
        }
        if (user.getFirstLogin() == null) {
            user.setFirstLogin(true);
        }

//        // 生成唯一的userId
//        user.setUserId(generateUniqueUserId());

        System.out.println("解析到用户数据：" + user);
        dataList.add(user);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("解析后用户数据条数：" + dataList.size());
        // 解析完成后批量保存
        userService.saveAllFromDTO(dataList);
    }

    @Override
    public int getImportedCount() {
        return 0;
    }

    @Override
    public int getIgnoredCount() {
        return 0;
    }

    // 生成唯一的以1开头的五位数userId
//    private String generateUniqueUserId() {
//        Random random = new Random();
//        int maxAttempts = 10;
//
//        for (int i = 0; i < maxAttempts; i++) {
//            String userId = String.valueOf(10000 + random.nextInt(90000));
//            if (!userService.existsByUserId(userId)) {
//                return userId;
//            }
//        }
//        throw new RuntimeException("生成唯一用户ID失败，请稍后重试");
//    }
}
